package com.beagle.njddapp.base;



import android.util.Log;

import com.beagle.njddapp.BuildConfig;
import com.blankj.utilcode.util.LogUtils;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

import static okhttp3.internal.Util.UTF_8;


/**
 * @author by lyy on 2019/9/12.
 *  okhttp  拦截器，主要功能为添加请求头,统一记录日志等等统一行为
 */
public class HttpInterceptor implements Interceptor {


    public static final String TAG = "NetWorkLogger";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        printRequestMessage(request);
        Response response = chain.proceed(request);
        printResponseMessage(response);
        return response;
    }
    /**
     * 打印请求消息
     *
     * @param request 请求的对象
     */
    private void printRequestMessage(Request request) {
        if (request == null) {
            return;
        }
        Log.i(TAG, "Url   : " + request.url().url().toString());
        Log.i(TAG, "Method: " + request.method());
        Log.i(TAG, "Heads : " + request.headers());
        RequestBody requestBody = request.body();
        if (requestBody == null) {
            return;
        }
        try {
            Buffer bufferedSink = new Buffer();
            requestBody.writeTo(bufferedSink);
            if (requestBody.contentType()!=null){
                Charset charset = requestBody.contentType().charset();
                charset = charset == null ? Charset.forName("utf-8") : charset;
                Log.i(TAG, "body: " + bufferedSink.readString(charset));
            }else {
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 打印返回消息
     *
     * @param response 返回的对象
     */
    private void printResponseMessage(Response response) {
        if (response == null || !response.isSuccessful()) {
            try {
                Log.i(TAG, "Response: " + response.body().source().readString(UTF_8));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        ResponseBody responseBody = response.body();
//        try {
//            Log.i(TAG, "Response: " + new String(responseBody.bytes()));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        long contentLength = responseBody.contentLength();
        BufferedSource source = responseBody.source();
        try {
            source.request(Long.MAX_VALUE); // Buffer the entire body.
        } catch (IOException e) {
            e.printStackTrace();
        }
        Buffer buffer = source.buffer();
        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
//        if (contentType != null) {
//            charset = contentType.charset();
//        }else {
//            charset=
//        }
//        if (charset != null) {
            String result = buffer.clone().readString(charset);
            e(result);
//        }else {
//            Log.i(TAG, "Response: " + buffer.clone().toString());
//        }
    }
    private static final Charset UTF8 = Charset.forName("UTF-8");

    public static void e( String msg) {

        int segmentSize =  3*1024;
        long length = msg.length();
        if (length <= segmentSize ) {// 长度小于等于限制直接打印
            LogUtils.d(TAG, msg);
        }else {
            while (msg.length() > segmentSize ) {// 循环分段打印日志
                String logContent = msg.substring(0, segmentSize );
                msg = msg.replace(logContent, "");
                LogUtils.d( TAG,logContent);
            }
            LogUtils.d( TAG,msg);
// 打印剩余日志
        }
    }
//
//    private static String requestValue;
//    private static String reponseValue;
//
//
//    @Override
//    public Response intercept(Chain chain) throws IOException {
//        //请求token
////        String token = SPUtils.getInstance(SPConstant.TOKEN).getString(SPConstant.TOKEN);
//
//        Request request = chain.request();
//       // LogUtils.d( "device_id="+BaseApplication.device);
//        //添加请求头
//       Request updateRequest = request.newBuilder()
////               .addHeader("device_id", "88888")
////               .addHeader("deviceType", "Android")
////               .addHeader("screenSize", ScreenUtils.getAppScreenWidth()+"x"+ScreenUtils.getAppScreenHeight())
////               .addHeader("version",BuildConfig.VERSION_NAME)
//               .build();
//
//        Response response =  chain.proceed(updateRequest);
//
//
//
//
//
//        if(BuildConfig.DEBUG){
//            //添加打印服务器返回的数据
//            ResponseBody responseBody = response.body();
//            long contentLength = responseBody.contentLength();
//            BufferedSource source = responseBody.source();
//            source.request(Integer.MAX_VALUE); // Buffer the entire body.
//            Buffer buffer = source.buffer();
//
//            LogUtils.d("请求参数："+ response.toString()+"\n"+"主体："+getRequestInfo(request)+"\n"+"返回数据："+getResponseInfo(response)+"\n"+updateRequest.headers());
//            requestValue =  response.toString();
//            reponseValue = getResponseInfo(response);
//            if (contentLength != 0) {
//                String msg = buffer.clone().readString(Charset.forName("UTF-8"));
//                LogUtils.d("请求参数："+response.toString()+"\n"+"返回数据："+msg+"\n"+updateRequest.headers());
//            }else {
//                LogUtils.d("请求参数："+response.toString());
//            }
//        }
//
//        return response;
//    }
//
//
//    /**
//     *
//     * @return
//     */
//    public static String getRequestParameter(){
//
//        return requestValue;
//    }
//    public static String getResponseParameter(){
//
//        return reponseValue;
//    }
//    /**
//     * 打印请求消息
//     *
//     * @param request 请求的对象
//     */
//    private String getRequestInfo(Request request) {
//        String str = "";
//        if (request == null) {
//            return str;
//        }
//        RequestBody requestBody = request.body();
//        if (requestBody == null) {
//            return str;
//        }
//        try {
//            Buffer bufferedSink = new Buffer();
//            requestBody.writeTo(bufferedSink);
//            Charset charset = Charset.forName("utf-8");
//            str = bufferedSink.readString(charset);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return str;
//    }
//
//    /**
//     * 打印返回消息
//     *
//     * @param response 返回的对象
//     */
//    private String getResponseInfo(Response response) {
//        String str = "";
//        if (response == null || !response.isSuccessful()) {
//            return str;
//        }
//        ResponseBody responseBody = response.body();
//        long contentLength = responseBody.contentLength();
//        BufferedSource source = responseBody.source();
//        try {
//            source.request(Long.MAX_VALUE); // Buffer the entire body.
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        Buffer buffer = source.buffer();
//        Charset charset = Charset.forName("utf-8");
//        if (contentLength != 0) {
//            str = buffer.clone().readString(charset);
//        }
//        return str;
//    }


}
